//---------------------------------------------------------------------
//  This file is part of the Background Motion solution.
// 
//  Copyright (C) Mindscape (TM).  All rights reserved.
//  http://www.mindscape.co.nz
// 
//  THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
//  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//  PARTICULAR PURPOSE.
//---------------------------------------------------------------------

using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;

using Mindscape.BackgroundMotion.Core;
using Mindscape.BackgroundMotion.Core.Model;
using Mindscape.BackgroundMotion.Website.Controllers;

namespace Mindscape.BackgroundMotion.Website.Infrastructure
{
  /// <summary>
  /// IInstanceContextInitializer is fired on each operation call to initialize the context for the operation
  /// </summary>
  public class ServiceModuleInitializer : IInstanceContextInitializer
  {
    public void Initialize(InstanceContext instanceContext, Message message)
    {
      SimpleServiceBroker broker = new SimpleServiceBroker();
      ServiceLocator.Initialize(broker);

      // These are the basic services we need into the container for our service operations
      broker.RegisterService<IContextItems>(new SimpleItemContext());
      broker.RegisterService<IUnitOfWorkFactory>(new DLinqUnitOfWorkFactory(Configuration.ConnectionString));
      broker.RegisterService<IRepositoryFactory>(new DLinqRepositoryFactory());
      broker.RegisterService<IContributionController>(new ContributionController());
    }
  }

  #region ServiceModuleBehaviorAttribute

  /// <summary>
  /// This attribute is applied to each service operation which needs module initialization
  /// </summary>
  public class ServiceModuleBehaviorAttribute : Attribute, IOperationBehavior
  {
    public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
    {
    }

    public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
    {
      dispatchOperation.Parent.InstanceContextInitializers.Add(new ServiceModuleInitializer());
    }

    public void Validate(OperationDescription operationDescription)
    {
    }
  }

  #endregion
}